<template>
  <!--弹出窗-->
  <modal ref="modal_1"
         :title="title"
         :isCloseConfirm="this.editable"
         :fullscreen="this.fullscreen"
         top="10%"
         width="50%"
         :close-on-click-modal="true"
         @modalOpened="opened"
         @modalClose="closed"
        >

    <avue-form :option="option"
               ref="form"
               v-model="form"
               @submit="onSubmit"
               :upload-before="uploadBefore"
               :upload-after="uploadAfter"

               :upload-exceed="uploadExceed"
               :upload-error="uploadError">
      <!--:upload-delete="uploadDelete"-->
      <!--<template   #imgList  >-->
        <!--<el-upload-->
                <!--ref="upload"-->
                <!--:disabled="!this.editable"-->
                <!--v-model:file-list="this.form.imgList"-->
                <!--class="upload-demo"-->
                <!--:limit="2"-->
                <!--:on-exceed="handleExceed"-->
                <!--:on-success="fileUploadSucc"-->
                <!--:http-request="fileUpload"-->
                <!--list-type="picture-card"-->
                <!--:is-preview="true"-->
                <!--accept=".jpg,.png"-->
                <!--:on-preview="handlePictureCardPreview"-->
        <!--&gt;-->
          <!--<el-icon><Plus /></el-icon>-->
        <!--</el-upload>-->
        <!--&lt;!&ndash;<el-dialog v-model="dialogVisible">&ndash;&gt;-->
          <!--&lt;!&ndash;<img w-full :src="dialogImageUrl" alt="Preview Image" />&ndash;&gt;-->
        <!--&lt;!&ndash;</el-dialog>&ndash;&gt;-->
        <!--<el-image -->
                <!--style="width: 100px; height: 100px"-->
                <!--:zoom-rate="1.2"-->
                <!--:preview-src-list="[dialogImageUrl]"-->
                <!--:initial-index="4"-->
                <!--fit="cover"-->
        <!--/>-->
      <!--</template>-->
      <!--<template   #avatar  >-->
      <!--<avue-upload action= '/blade-resource/file/upload'-->
                   <!--v-model="this.form.avatar"-->
                   <!--list-type='picture-card'></avue-upload>-->
      <!--</template>-->
    </avue-form>

    <!--底部按钮块, 默认只有"取消"按钮-->
    <template #footerButton>
      <el-button
              type="primary"
              v-if="(permission.machine_add || permission.machine_edit) && editable"
              :loading="btnLoading"
              @click="this.$refs.form.submit()"
      >保 存
      </el-button>
      <el-button @click="$refs.modal_1.handleClose()">关闭</el-button>
    </template>
  </modal>
</template>

<script>
  import {getList, getDetail, add, update, remove} from "@/api/anwise/machine";
  import {mapGetters} from "vuex";
  import { getToken } from 'utils/auth';
  import {upload} from "@/api/tool/file";

  export default {
    data() {
      return {
        emits: ["success"],
        editable: false,
        title: "机器设备信息",
        isCloseConfirm: false,
        fullscreen: false,
          btnLoading: false,
          dialogVisible:false,
          dialogImageUrl:'',
          headers:{'Content-Type':'multipart/form-data','Blade-Auth':'bearer '+ getToken()},
        form: {imgList:[]},
        query: {},
        loading: true,
        option: {
          height: 'auto',
          calcHeight: 30,
          labelWidth: 150,
          menuWidth: 120,
          submitBtn: false,
          emptyBtn: false,
          column: [
              {
                  label: "设备编号",
                  prop: "resourceId",
                  type: "input",
                  disabled:true,
                  placeholder: ' ',
              },
              {
                  label: "设备名称",
                  prop: "resourceName",
                  type: "input",
                  maxlength: 500,
                  rules: [{
                      required: true,
                      message: "请输入设备名称",
                      trigger: "blur"
                  }],
              },
              {
                  label: "购买日期",
                  prop: "buyDate",
                  type: "date",
                  valueFormat: 'YYYY-MM-DD',
                  format:'YYYY-MM-DD',
                  rules: [{
                      required: true,
                      message: "请输入购买日期",
                      trigger: "blur"
                  }],
              },
              {
                  label: "设备颜色",
                  prop: "resourceColor",
                  type: "select",
                  dicUrl: "/blade-system/dict-biz/dictionary?code=color",
                  filterable: true,
                  props: {
                      label: 'dictValue',
                      value: 'dictValue',
                  },
                  dataType: 'string',
                  rules: [{
                      required: false,
                      message: "请输入设备颜色",
                      trigger: "blur"
                  }],
              },
              {
                  label: "吨位",
                  prop: "weight",
                  type: "input",
                  maxlength: 50,
              },
              {
                  label: "所在位置",
                  prop: "addr",
                  type: "input",
                  maxlength: 500,
              },
              {
                  label: "保修期限",
                  prop: "okDate",
                  type: "date",
                  valueFormat: 'YYYY-MM-DD',
                  format:'YYYY-MM-DD',
              },
              {
                  label: "机器编号",
                  prop: "macNo",
                  type: "input",
                  maxlength: 50,
                  rules: [{
                      required: true,
                      message: "请输入机器编号",
                      trigger: "blur"
                  }],
              },
              {
                  label: "资产编号",
                  prop: "macCount",
                  type: "input",
                  maxlength: 50,
                  rules: [{
                      required: true,
                      message: "请输入资产编号",
                      trigger: "blur"
                  }],
              },
              {
                  label: "机器状态",
                  prop: "macStatus",
                  type: "select",
                  dicUrl: "/blade-system/dict-biz/dictionary?code=machine_status",
                  filterable: true,
                  props: {
                      label: 'dictValue',
                      value: 'dictValue',
                  },
                  dataType: 'string',
                  rules: [{
                      required: true,
                      message: "请选择机器状态",
                      trigger: "blur"
                  }],
              },
              {
                  label: "报废时间",
                  prop: "scrapDate",
                  type: "date",
                  valueFormat: 'YYYY-MM-DD',
                  format:'YYYY-MM-DD',
              },
              {
                  label: "备注",
                  prop: "remark",
                  type: "textarea",
                  minRows:2,
                  span:24,
                  maxlength: 2000,
              },
              {
                  label: "设备图片",
                  prop: "fileList",
                  type: "upload",
                  listType: 'picture-card',
                  action: '/blade-resource/file/upload',
                  accept:'.png,.jpg,.jpeg,.bpm,.gif',
                  // fileType: 'img',
                  tip: '只能上传png/jpg/jpeg/bpm/gif，且不超过10M，数量不超过10张',
                  limit: 10,
                  fileSize: 10000,
                  span: 24,
                  propsHttp: {
                      res: 'data',
                      url: 'url',
                  },
                  // canvasOption: {
                  //     text: 'ANWISE ERP CLOUD',
                  //     ratio: 0.1,
                  // },
              },
              {
                  label: "创建人员",
                  prop: "createUserName",
                  type: "input",
                  display:false,
                  disabled:true,
              },
              {
                  label: "创建时间",
                  prop: "createTime",
                  type: "input",
                  display:false,
                  disabled:true,
              },
          ]
          },
          data: []
        };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.validData(this.permission.machine_add, false),
          viewBtn: this.validData(this.permission.machine_view, false),
          delBtn: this.validData(this.permission.machine_delete, false),
          editBtn: this.validData(this.permission.machine_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
        onSubmit(form, done) {
            console.log(form);
            this.btnLoading = true;
            if (form.imgList) {
                form.imgList.forEach((item, index) => {
                    if (!form.fileList.includes(item.url)) {
                        form.imgList.splice(index, 1);
                    }
                })
            }
            this.$nextTick(()=> {
                update(form).then(res => {
                    done();
                    this.btnLoading = false;
                    if (res.data.success) {
                        this.$message({
                            type: "success",
                            message: res.msg || "保存成功!"
                        });
                        setTimeout(() =>{
                            this.$refs.modal_1.hide();
                        },1000)
                    } else {
                        this.$message({
                            type: "error",
                            message: res.msg || "保存失败!"
                        });
                    }
                }).catch(err => {
                    console.log(err)
                    done();
                    this.btnLoading = false;
                })
            });


        },
        show(option) {
            if (option.id) {
                setTimeout(() => {
                    getDetail(option.id).then(res =>{
                        if (res.data.success) {
                            this.form = res.data.data;
                            this.form.imgList.forEach(item =>{
                                if (!this.form.fileList) {
                                    this.form.fileList = [];
                                }
                                this.form.fileList.push(item.url);
                            })

                            this.findObject(this.option.column, 'createUserName').display=true;
                            this.findObject(this.option.column, 'createTime').display=true;
                        }
                    })
                }, 500);
            } else {
                this.form={}
                this.findObject(this.option.column, 'createUserName').display=false;
                this.findObject(this.option.column, 'createTime').display=false;
                this.findObject(this.option.column, 'resourceId').display=false;
            }
            this.title = option.title;
            this.type = option.type;
            this.option.detail = this.type === "view";
            this.editable = this.type !== "view";
            this.$refs.modal_1.show();
        },
      rowSave(row, done, loading) {
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      },
        opened() {
            console.log("opened")
        },
        closed() {
            this.form = {};
            this.$emit("success");
        },
        uploadBefore (file, done, loading, column) {
            console.log(file, column)
            // var newFile = new File([file], '1234', { type: file.type });
            done(file)
            // this.$message.success('上传前的方法')
        },
        uploadAfter (res, done, loading, column) {
            console.log(res, column)
            if (!this.form.imgList) {
                this.form.imgList = [];
            }
            this.form.imgList.push(res);
            done()
            this.$message.success('上传成功！')
        },
        uploadDelete (file, column) {
            console.log(file, column)
            return new Promise((resolve, reject) => {
                if (this.form.imgList) {
                    this.form.imgList.forEach(item => {
                        if (item.url === file.url) {
                            console.log("删除项", item.url, file.url);
                            console.log(this.form.imgList.splice(item,1));
                        }
                        console.log(this.form.imgList);
                    })
                  }
                  resolve();
              });

        },
        uploadExceed (limit, files, fileList, column) {
            console.log(limit, files, fileList, column)
            this.$message.error('超出上传限制文件数量')
        },
        uploadError (error, column) {
            this.$message.error('上传失败！')
            console.log(error, column)
        }
    },
  };
</script>

<style>
</style>
